﻿using NET6.WebAPI.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace NET6.WebAPI.Extensions
{
    public static class JsonExtension
    {
        /// <summary>
        /// Object 转 JSON 格式 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object? obj)
        {
            if (obj != null)
            {
                var settings = new JsonSerializerSettings
                {
                    DateFormatString = DateTimeHelper._dateTime
                };

                return JsonConvert.SerializeObject(obj, settings);
            }

            return "";
        }

        /// <summary>
        /// JSON 转对象类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T ToObject<T>(this string? json) where T : new()
        {
            if (!string.IsNullOrWhiteSpace(json))
            {
                var obj = JsonConvert.DeserializeObject<T>(json);
                if (obj != null)
                {
                    return obj;
                }
            }

            return new T();
        }

        /// <summary>
        /// 判断 JToken 的值是否不为 NULL 和空字符串 
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool HasValue(this JToken? value)
        {
            return value != null && !string.IsNullOrWhiteSpace(value.ToString());
        }
    }
}
